package com.qf.flash.ui.mine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qf.flash.R;
import com.qf.flash.model.QrCodeBean;
import com.qf.flash.mvp.contract.MyInvitationContract;
import com.qf.flash.mvp.presenter.MyInvitationPresenter;
import com.qf.flash.utils.AppToast;
import com.qf.flash.utils.ImageLoader;
import com.qf.flash.utils.ShareUtils;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.widget.CustomProgressDialog;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qf.flash.app.MyApp.mWxApi;

/**
 * 我的推广码
 */
public class MyInvitationActivity extends BaseActivity implements MyInvitationContract.View {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.tv_me)
    TextView tvMe;
    @BindView(R.id.ll_share_wx)
    LinearLayout llShareWx;
    @BindView(R.id.ll_share_pyq)
    LinearLayout llSharePyq;
    private String imgUrl = "";
    private MyInvitationPresenter invitationPresenter;
    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/shandian/";
    private CustomProgressDialog dialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_invitation;
    }

    @Override
    protected void initInject() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        super.initInject();
        invitationPresenter = new MyInvitationPresenter();
        initPresenters(invitationPresenter);
        dialog = new CustomProgressDialog(this);
        dialog.setTipText("启动分享中...");
    }

    @Override
    protected void initViewAndData() {
        invitationPresenter.getQRCode();
    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, MyInvitationActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setToolbarCustomTheme(R.color.white);
    }

    @Override
    protected void onPause() {
        super.onPause();
        setToolbarCustomTheme(R.color.black);
    }

    protected void setToolbarCustomTheme(int color) {
        Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.common_back);
        if (upArrow != null) {
            upArrow.setColorFilter(ContextCompat.getColor(this, color), PorterDuff.Mode.SRC_ATOP);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setHomeAsUpIndicator(upArrow);
            }
        }
    }


    @OnClick({R.id.iv_back, R.id.ll_share_wx, R.id.ll_share_pyq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_share_wx:// 分享微信
                if (!mWxApi.isWXAppInstalled()) {
                    AppToast.showToast("您还未安装微信！");
                    return;
                } else {
                    dialog.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Bitmap bitmap = BitmapFactory.decodeStream(getImageStream(imgUrl));
                                saveFile(bitmap, "qr.jpg", 0);
                                dialog.dismiss();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();

                }
                break;
            case R.id.ll_share_pyq:// 分享朋友圈
                if (!mWxApi.isWXAppInstalled()) {
                    AppToast.showToast("您还未安装微信！");
                    return;
                } else {
                    dialog.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Bitmap bitmap = BitmapFactory.decodeStream(getImageStream(imgUrl));
                                saveFile(bitmap, "qr.jpg", 1);
                                dialog.dismiss();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                }
                break;
        }

    }

    @Override
    public void showQrCode(QrCodeBean codeBean) {
        ImageLoader.load(this, codeBean.getUrl(), ivCode);
        imgUrl = codeBean.getUrl();
        tvMe.setText("邀请码：" + codeBean.getCode());
    }


    //获取url流
    public InputStream getImageStream(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return conn.getInputStream();
        }
        return null;
    }

    //  下载到sd卡
    public void saveFile(Bitmap bm, String fileName, int type) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        ShareUtils.imageShare(myCaptureFile.getPath(), type);
    }

}
